#include "distribute_download.h"
#include <custom_head.h>

int sock_init(char*ip, char *port) {
  int sockfd = socket(AF_INET, SOCK_STREAM, 0);
  int flag = 1;
  setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
  struct sockaddr_in addr;
  addr.sin_family = AF_INET;
  addr.sin_port = htons(atoi(port));
  addr.sin_addr.s_addr = INADDR_ANY;
  bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));
  listen(sockfd, 100);
  return sockfd;
}

int epoll_add(int epfd, int fd) {
  struct epoll_event event;
  event.events = EPOLLIN;
  event.data.fd = fd;
  epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &event);
  return 0;
}

int epoll_del(int epfd, int fd) {
  epoll_ctl(epfd, EPOLL_CTL_DEL, fd, NULL);
  return 0;
}

int main(int argc, char *argv[]) {
  ARGS_CHECK(argc, 4);
  char *file_path = argv[2];
  int chunk_size = atoi(argv[3]) * 1024 * 1024;

  int sockfd = sock_init((in_addr_t) 0x00000000,argv[1]);
  int epfd = epoll_create(1);
  epoll_add(epfd, sockfd);

  struct epoll_event ready[1024];

  while (1) {
    int readynum = epoll_wait(epfd, ready, 1024, -1);
    for (int i = 0; i < readynum; i++) {
      int client_sock = ready[i].data.fd;
      if (client_sock == sockfd) {
        int netfd = accept(sockfd, NULL, NULL);
        epoll_add(epfd, netfd);

      } else {
        char request[MAX_REQ_SIZE];
        int len = recv(client_sock, request, MAX_REQ_SIZE, 0);
        request[len] = '\0';

        // 解析请求格式 "GET chunk_index"
        int chunk_index;
        if (sscanf(request, "GET %d", &chunk_index) != 1) {
          fprintf(stderr, "invalid request: %s\n", request);
          close(client_sock);
          continue;
        }
     
        int fd = open(file_path,O_RDWR);
        if (!fd) {
          fprintf(stderr, "open file error.\n");
          close(client_sock);
          continue;
        }
        lseek(fd, chunk_index * chunk_size, SEEK_SET);

        
        char buffer[CHUNK_SIZE];
        int bytes_read = read(fd,buffer,chunk_size);
        close(fd);

        send(client_sock, buffer, bytes_read, 0);
        printf("Server has sent %d (%d Bytes)\n", chunk_index, bytes_read);
        close(client_sock);
      }
    }
  }
  close(sockfd);
  return 0;
}
